package aliyun

import (
	"encoding/json"
	"sync"
	"time"

	"github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/astaxie/beego/logs"
)

type TokenManage struct {
	token  Token
	locker sync.RWMutex
}

type Token struct {
	ExpireTime int64  `json:"ExpireTime"`
	Id         string `json:"Id"`
	UserId     string `json:"UserId"`
}

func newToken() *TokenManage {

	newToken := &TokenManage{}
	newToken.getNewToken()

	return newToken
}

func (t *TokenManage) getNewToken() {

	client, err := sdk.NewClientWithAccessKey("cn-shanghai", accessKeyId, accessKeySecret)
	if err != nil {
		logs.Error("newClient failed:%v", err)

	}

	request := requests.NewCommonRequest()
	request.Method = "POST"
	request.Domain = "nls-meta.cn-shanghai.aliyuncs.com"
	request.Version = "2018-05-18"
	request.PathPattern = "/pop/2018-05-18/tokens"
	response, err := client.ProcessCommonRequest(request)
	if err != nil {
		logs.Error("porcess common request failed:%v", err)

		return
	}

	logs.Debug("token get:%v", response.GetHttpContentString())

	/*
			 "Token": {
		        "ExpireTime": 1527592757,
		        "Id": "124fc7526f434b8c8198d6196b0a1c8e",
		        "UserId": "123456789012"
		    }
	*/

	type tokenResp struct {
		Token Token `json:"Token"`
	}

	res := &tokenResp{}
	err = json.Unmarshal(response.GetHttpContentBytes(), res)
	if err != nil {
		logs.Error("recv response is not :%v", err)

		return
	}

	t.locker.Lock()
	defer t.locker.Unlock()

	t.token = res.Token

}

func (t *TokenManage) getToken() string {

	now := time.Now()
	timeOut := t.token.ExpireTime - now.Unix()

	if timeOut <= 0 {
		//立即更新
		t.getNewToken()

	} else if timeOut < 10 {

		//延时更新1毫秒后更新
		go func() {
			time.Sleep(time.Millisecond)
			t.getNewToken()
		}()
	}

	t.locker.RLock()
	defer t.locker.RUnlock()

	return t.token.Id
}
